<?php
declare(strict_types=1);

namespace app\admin\controller;

use app\admin\validate\LoginValidate;
use app\common\controller\BaseController;
use app\common\service\AdminService;
use app\common\utils\JsonResponse;
use think\App;
use think\facade\Request;
use app\common\model\Admin;

class Login extends BaseController
{
    protected AdminService $adminService;
    
    public function __construct(App $app, AdminService $adminService)
    {
        parent::__construct($app);
        $this->adminService = $adminService;
    }
    
    /**
     * 管理员登录
     */
    public function login()
    {
        $params = Request::post();
        
        // 使用验证器验证参数
        try {
            validate(LoginValidate::class)
                ->scene('login')
                ->check($params);
        } catch (\think\exception\ValidateException $e) {
            return JsonResponse::error($e->getMessage());
        }

        try {
            $result = $this->adminService->login($params['username'], $params['password']);
            return JsonResponse::success($result);
        } catch (\Exception $e) {
            return JsonResponse::error($e->getMessage());
        }
    }

    /**
     * 退出登录
     */
    public function logout()
    {
        try {
            $token = Request::header('Authorization');
            if (empty($token)) {
                return JsonResponse::error('退出登录失败');
            }
            
            // 去掉可能存在的 Bearer 前缀
            $token = str_replace('Bearer ', '', $token);
            
            if ($this->adminService->logout($token)) {
                return JsonResponse::success([], '退出成功');
            }
            return JsonResponse::error('退出登录失败');
            
        } catch (\Exception $e) {
            return JsonResponse::error($e->getMessage());
        }
    }
} 